<?php

/**
 * Wlib Framework
 *
 *
 * @category   Wlib
 * @package    Wlib_Validate
 */


/**
 * @see Zend_Validate_Abstract
 */
require_once 'Zend/Validate/Abstract.php';


/**
 * Валидатор. Проверяет является ли значение поля уникальным
 *
 * @category   Wlib
 * @package    Wlib_Validate
 */
class Wlib_Validate_UniqueFieldValue extends Zend_Validate_Abstract
{

    const NOT_UNIQUE = 'uniqueFieldValueNotUnique';

    /**
     * @var array
     */
    protected $_messageTemplates = array(
        self::NOT_UNIQUE => "'%value%' is not unique",
    );

     /**
     * Model
     *
     * @var Wlib_Db_Table
     */
    protected $_model;

    /**
     * @todo комментарии к полям
     */
    protected $_fieldName;
    protected $_excludePrimaryName;
    protected $_excludePrimaryValue;

    protected $_excludeParams = null;
    /**
     * Sets validator options
     *
     * @param  integer $min
     * @param  integer $max
     * @return void
     */

    /**
     * Установка атрибутов валидатора
     *
     * @param Wlib_Db_Table $model
     * @param string $fieldName
     * @param string $excludePrimaryName
     * @param string $excludePrimaryValue
     */
    public function __construct($model, $fieldName, $excludePrimaryName = null, $excludePrimaryValue = null)
    {
        /**
         * @todo сделать сетеры
         */

        $this->_model = $model;
        $this->_fieldName = $fieldName;

        if(is_array($excludePrimaryName) && null === $excludePrimaryValue) {
            $this->_excludeParams = $excludePrimaryName;
        } else {
            $this->_excludeParams = array(
                $excludePrimaryName => $excludePrimaryValue
            );
        }
    }


    /**
     * @todo написать описание к функции
     */

    /**
     * Defined by Zend_Validate_Interface
     *
     *
     * @param  string $value
     * @return boolean
     */
    public function isValid($value)
    {
        if(!empty($value)) {
            $valueString = (string) $value;
            $this->_setValue($valueString);

            $where = array();

            $pat = ' `' . $this->_fieldName . '` = ? ';
            $where[] = $this->_model->getAdapter()->quoteInto($pat, $value);

            foreach($this->_excludeParams as $excludeField => $excludeValue) {
                $where[] = $this->_model->getAdapter()->quoteInto("`$excludeField` != ?", $excludeValue);
            }
            $rowData = $this->_model->fetchRow($where);
            if(sizeof($rowData)) {
                $this->_error(self::NOT_UNIQUE);
            }
        }

        if (count($this->_messages)) {
            return false;
        } else {
            return true;
        }
    }

}
